import glob,os,sys,os.path
import ConfigParser
import shutil

def getDataFromPrototypes(proto_file):
    filelist=[]
    dir = os.path.dirname(proto_file)
    
    config = ConfigParser.ConfigParser()
    config.readfp(open(proto_file))
    
    
    filelist=glob.glob(os.path.join(dir,"*"))        
    filelist_low=[f.lower() for f in filelist]
        
    for section in config.sections():
        if config.has_option(section,'resources'):            
            value=config.get(section,'resources')
            for resId in eval(value):
                name=os.path.join(dir,resId.split(":")[0])                                
                filelist.append(name)
                #implement a case check for unix compatibility
                if not name in filelist:
                    print "A ressource(%s) has not been found"%name
                    if not name.lower() in filelist_low:
                        print "The file name is not found"
                    else:
                        print "A case error has been detected. Case dependant os issue detected."
                    sys.exit(1)
    return [(dir,filelist)]

def getDataFromFileSystem(dir):
    result=list()
    filelist=list()
    for item in glob.glob(os.path.join(dir,"*")):        
        if os.path.isdir(item):
            result+=getdata(item)
        else:
            filelist.append(item)
    if(len(filelist)):
        result.append((dir,filelist))
    return result
            
    
#automatic build if not arguments are not provided
if len(sys.argv) == 1:
    sys.argv.append("py2exe")

#setup the path
os.chdir(sys.path[0])

print "===== Clean outputs directories ====="
shutil.rmtree("build",True) 
shutil.rmtree("dist",True) 
os.system("del *.pyc *.pyo *.log *.profile /s")
print "===== Search for ressource files ====="
data_files=getDataFromPrototypes(os.path.join("res","prototypes.cfg"))+getDataFromFileSystem("maps")+getDataFromFileSystem("ia")
print "===== Compute dependances ====="
#build the release
import py2exe
from distutils.core import setup
setup(  version = "0.5",
        description = "borgwar is a IA fight ground. It includes a map editor.",
        name="borgwar",
        console=['borgwar.py','profile.py'], 
        data_files=data_files,
        options = {"py2exe": {"compressed": 1,"optimize": 2}}
        )
print "===== Clean build directory ====="
shutil.rmtree("build",True) 
